/*
 * @name: 管理后台登陆接口
 * @content:
 * @Author: joyce
 * @Date: 2020-03-11 11:22:37
 */
const express = require(`express`);
const router = express.Router();
let jwt = require("jsonwebtoken");
let config = require("../libs/config");
const user_login = require("../model/system/user_login");
const decrypt = require("../utils/crypto");
/* GET users listing. */
//管理后台登录
router.post("/api/v1/user/login", async (req, res, next) => {
  //
  try {
    console.log("req.body", req.body);
    let user = await user_login
      .findOne({
        userName: req.body.username,
      })
      .populate({ path: "role" });
    console.log("user", user);
    //  何时返回token  要根据自己的业务逻辑
    if (user !== null) {
      console.log(req.body);
      // 获取到用户信息后进行解密密码校对
      let password = req.body.password;
      console.log(user.password);
      if (user.password === password) {
        if (!user.status) {
          res.json({
            code: 4022,
            message: "该账号已下线，若要登录请联系管理员!",
          });
          return;
        }

        let token = jwt.sign(
          {
            _id: user._id,
          },
          config.secretOrPrivateKey,
          {
            expiresIn: "1 days",
          }
        );
        console.log(token);
        res.json({
          code: 2000000,
          token: user._id,
          user: user.toJSON(),
        });
      } else {
        res.json({
          code: 4022,
          message: "用户不存在,请重新登陆!",
        });
      }
    }
  } catch (err) {
    console.log(err);
    res.json({
      code: 4022,
      message: "用户不存在,请重新登陆!",
    });
  }
});

//管理后台获得登录信息
router.get("/api/v1/user/info", async (reqs, res, next) => {
  console.log("reqs.query", reqs.query);
  var user = await user_login.findOne({
    _id: reqs.query.token,
  });
  console.log(user);
  if (user !== null) {
    res.json({
      code: 2000000,
      data: user,
    });
  }

  //
});
//管理后台获得登录信息
router.post("/api/v1/user/logout", async (req, res, next) => {
  res.json({
    code: 2000000,
    data: "success",
  });

  //
});

module.exports = router;
